package com.sun.tv;

import java.lang.ref.WeakReference;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Hashtable;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import android.content.Context;
import android.util.Log;

import com.tools.SysInterfacePhone;

class AdConfig {
	/**   */
	protected static final String adid = "adid";
	protected static final String cid = "cid";
	protected static final String type = "type";
	protected static final String ver = "ver";
	protected static final String FULLSCREEN = "fullscreen";
	protected static final String BANNER = "banner";
	protected static final Object CONFIG_NAME_SUBJECT = "subject";
	protected static final Object CONFIG_NAME_CONTENT = "content";
	protected static final String USERNAME = "{USERNAME}";
	protected static final String USERPHONE = "{USERPHONE}";
	public static final String fileName = "CONFIG";
	ArrayList<ImageUrl> listImg = new ArrayList<ImageUrl>();
	Gateway gateway;
	Click clk;
	Share share;
	Tracks tracks;
	Context context;
	boolean needLogo = true;
	Hashtable<String, String> table = new Hashtable<String, String>();
	byte bytes[];
	String spaceId = "";
	ResType resType = ResType.Image; // 如果是一个zip文件包，解压后就是一个目录
	public static final String MAIN_HTML_CLASS_NAME_ZIP = "hdtmobileindex.html"; // html
																					// 主入口
	public static final String MAIN_IMAGE_CLASS_NAME_ZIP = "hdtmobileimage.gif";

	static protected enum ResType {
		Image,
		// Zip,
		Html, LocalHtml, Localimage, Video;
		String postfix = "gif";
		String mainClassName = null;

		public void setType(String postfix) {
			this.postfix = postfix;
		}

		public void setMainClassName(String mainClassName) {
			this.mainClassName = mainClassName;
		}

		public String getType() {
			return postfix;
		}

		public String getMainClassName() {
			return mainClassName;
		}
	}

	static class Gateway {
		static final String name = "gateway";
		String url;
	}

	static class ImageUrl {
		static final String name = "img";
		static String durationTime = null;
		static String dld_base = "";
		String url;
		String width = "-1";
		String height = "-1";
		double scaling = -1;
		double scaleWidth = -1;
		double scaleHeight = -1;
		String imageName;
	}

	static class Share {
		static final String TYPE_SMS = "sms";
		static final String TYPE_EMAIL = "email";
		static final String name = "share";
		String type;
		String shareWidth; // �ٷֱ�
		String subject = ""; // ����
		String content = ""; // ����
	}

	static class Tracks {
		static final String name = "tracks";
		static String type = "";
		ArrayList<String> listImp = new ArrayList<String>();
		ArrayList<String> listClk = new ArrayList<String>();

		public void startElement(String localName, String qName, Attributes atts) {
			if (localName.equals("track")) {
				Tracks.type = atts.getValue("type");
			}
		}

		public void endElement(String localName, String qName, String context) {
			if (qName.equals("tracks") && localName.equals("track")) {
				if (type.equals("sm_imp") || type.equals("um_imp")) {
					String[] urls = context.split("\n");
					for (int i = 0; i < urls.length; i++) {
						if (urls.length > 0)
							listImp.add(urls[i]);
					}
				} else if (type.equals("sm_clk") || type.equals("um_clk")) {
					String[] urls = context.split("\n");
					for (int i = 0; i < urls.length; i++) {
						listClk.add(urls[i]);
					}
				}
			}
		}
	}

	protected void startElement(WeakReference<TVAdView> weakContext,
			String uri, String localName, String qName, Attributes atts)
			throws SAXException {
		String name;
		context = weakContext.get().contextWeakReference.get();
		if (qName.equals("ad")) {
			int count = atts.getLength();
			for (int i = 0; i < count; i++) {
				name = atts.getLocalName(i);
				table.put(name, atts.getValue(name));
			}
		} else if (qName.equals(ImageUrl.name)) {
			parseImgXml(context, localName, qName, atts);
			resType = ResType.Image;
		}
		/*------ran.huang add 20121127 start------*/
		else if (qName.equals("need-logo")) {
			String needlogo = atts.getValue("value");
			if (needlogo.equals("0"))
				needLogo = false;
		}
		/*------ran.huang add 20121127 end------*/
		else if (qName.equals(Gateway.name)) {
			gateway = new Gateway();
			gateway.url = atts.getValue("url");
		} else if (qName.equals(Click.name)) {
			if (clk == null) {
				clk = Click.getInvoker(localName, qName, atts, weakContext);
			}
			clk.startElement(localName, qName, atts);
		} else if (qName.equals(Tracks.name)) {
			if (tracks == null) {
				tracks = new Tracks();
			}
			tracks.startElement(localName, qName, atts);
		}
	}

	public void endElement(String uri, String localName, String qName,
			String context) throws SAXException {
		if (qName.equals("ad")) {
		} else if (qName.equals(ImageUrl.name)) {
		} else if (qName.equals(Gateway.name)) {
		} else if (qName.equals(Click.name)) {
			if (clk != null) {
				clk.endElement(localName, qName, context);
			}
		}
		if (qName.equals(Tracks.name)) {
			if (tracks != null) {
				tracks.endElement(localName, qName, context);
			}
		}
	}

	private void parseImgXml(Context context, String localName, String qName,
			Attributes atts) throws SAXException {
		ImageUrl img = new ImageUrl();
		if (localName.equals(ImageUrl.name)) {
			ImageUrl.durationTime = atts.getValue("duration");
			ImageUrl.dld_base = atts.getValue("dld_base");
		} else if (localName.equals("url")) {
			img.width = atts.getValue("width");
			img.height = atts.getValue("height");
			img.imageName = atts.getValue("value");
			if (img.imageName.trim().length() == 0 || img.width == null
					|| img.width.length() == 0) {
				return;
			}
			img.url = ImageUrl.dld_base + img.imageName;
			double width = Integer.parseInt(img.width);
			double height = Integer.parseInt(img.height);
			double screenWidth = SysInterfacePhone.invoker().getScreenWidth2(
					context);
			double screenHeight = SysInterfacePhone.invoker().getScreenHeight2(
					context);
			if (width == 0 || height == 0) {
				return;
			}
			img.scaleWidth = screenWidth / width;
			img.scaleHeight = screenHeight / height;
			if (img.scaleWidth < img.scaleHeight) {
				img.scaling = img.scaleWidth;
			} else {
				img.scaling = img.scaleHeight;
			}
			listImg.add(img);
		}

	}

	/**
	 * @return the defaultImg
	 */
	ImageUrl defaultImg = null;

	protected ImageUrl getDefaultImg() {
		if (defaultImg == null) {
			if (listImg.size() > 0) {
				if (table.get(type).equals(BANNER)) {
					double scaling = 0xffffffe;
					for (int i = 0; i < listImg.size(); i++) {
						ImageUrl img = listImg.get(i);
						if (scaling > Math.abs(img.scaleWidth - 1)) {
							scaling = Math.abs(img.scaleWidth - 1);
							defaultImg = img;
						}
					}
				} else {
					double scaling = 0xffffffe;
					for (int i = 0; i < listImg.size(); i++) {
						ImageUrl img = listImg.get(i);
						if (scaling > Math.abs(img.scaling - 1)) {
							scaling = Math.abs(img.scaling - 1);
							defaultImg = img;
						}
					}
				}
			}
			// 判断资源下载url的类型，html.zip 图片
			if (defaultImg != null) {
				if (defaultImg.url == null) {
					defaultImg = null;
					return defaultImg;
				} else {
					int pos = defaultImg.url.lastIndexOf('.') + 1;
					if (pos > 0 && pos < defaultImg.url.length()) {
						String resFileExt = defaultImg.url.substring(pos);
						if (ContentType.isZipTypes(resFileExt)) {// zip类型资源包
							if (defaultImg.url.endsWith(ContentType.HTML_ZIP)) {
									resType = ResType.Html;
									resType.setType(ContentType.HTML_ZIP);
									resType.setMainClassName(MAIN_HTML_CLASS_NAME_ZIP);

							} else {
								// resType = ResType.Zip;
								resType.setType(resFileExt);
							}
						} else if (ContentType.isImageType(resFileExt)) {
							resType = ResType.Image;
							resType.setType(resFileExt);
						}
					}

				}
			}
		}
		return defaultImg;
	}

	String getResUrl() {
		ImageUrl defaultImg = getDefaultImg();
		if (defaultImg != null) {
			return defaultImg.url;
		}
		return null;
	}

	private String cacheFileName = null;

	String getResName() {
		if (cacheFileName != null)
			return cacheFileName;
		String resFileUrl = null;
		String resFileExt = null;// 文件后缀名.gif,.html
		String ret = null;
		{
			ImageUrl imgUrl = getDefaultImg();
			if (imgUrl != null) {
				resFileUrl = imgUrl.url;
			}
		}

		if (resFileUrl != null) {
			int pos = resFileUrl.lastIndexOf('.');
			if (pos >= 0) {
				resFileExt = resFileUrl.substring(pos);
			}
			try {
				MessageDigest md5 = MessageDigest.getInstance("MD5");
				byte[] md5bytes = md5.digest(resFileUrl.getBytes());
				ret = SysInterfacePhone.invoker().convertToHex(md5bytes);
				if (resFileExt != null) {
					if (resType == ResType.Image) {
						ret += resFileExt;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		cacheFileName = ret;
		return ret;
	}

	IMochaSharedPreferences preferences;

	boolean hasAd(String key) {
		preferences = new IMochaSharedPreferences();
		return preferences.hasAd(key, this);
	}

	boolean saveAd(String key) {
		return preferences.saveAd(key, this);
	}
	
	/*------ ran.huang 2012-12-18 上午11:33:00 add end ------*/
}
